package com.xcap.security.datasourceauthentication.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;

/**
 * 创建验证码过滤器
 */
@Component
@Slf4j
//所有的请求路径都走这个
public class ValidateFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //判断路径是否是/login/doLogin
        String requestURI = request.getRequestURI();
        if (!"/login/doLogin".equals(requestURI)) {// 不是登录请求，直接放行  requestURI
            doFilter(request, response, filterChain);//直接 下一个过滤器
            return;
        }
        // 校验验证码
        validateCode(request,response,filterChain);

    }

    public static void main(String[] args) {
        ArrayList<String> strings = new ArrayList<>();
        strings.add("abc");
        strings.add("def");
        strings.add("ghi");
        System.out.println(strings.toString());
    }

    private void validateCode(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        // 1从前端获取验证码

        String enterCaptchaCode = request.getParameter("code");
        //2 从session中获取验证码
        HttpSession session = request.getSession();
        String loginCaptchaSessionCode = (String)session.getAttribute("LOGIN_CAPTCHA_CODE");
        log.info("用户输入的验证码为：{}，session中的验证码为：{}",enterCaptchaCode,loginCaptchaSessionCode);
        //移除错误信息
        session.removeAttribute("captchaCodeErrorMsg");
        //3 3判单二者是否相等
        if (!StringUtils.hasText(loginCaptchaSessionCode)) {
            session.removeAttribute("captchaCodeErrorMsg");
        }
        if (!StringUtils.hasText(enterCaptchaCode)||!StringUtils.hasText(loginCaptchaSessionCode)
        ||  !enterCaptchaCode.equalsIgnoreCase(loginCaptchaSessionCode)) {
            session.setAttribute("captchaCodeErrorMsg","输入验证码错误");
            //验证码错误进行重定向
            response.sendRedirect("/login/toLogin");
        }else{
            filterChain.doFilter(request,response);
        }
    }
}
